package cn.yikaojiuguo.student.adapter;

import android.content.Context;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;

import com.google.gson.Gson;
import com.qiniu.android.http.ResponseInfo;
import com.qiniu.android.storage.UpCompletionHandler;

import org.json.JSONObject;

import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.List;

import cn.yikaojiuguo.student.R;
import cn.yikaojiuguo.student.app.YiKaoApplication;
import cn.yikaojiuguo.student.bean.AskTeachers;
import cn.yikaojiuguo.student.bean.Category;
import cn.yikaojiuguo.student.bean.MessageEvent;
import cn.yikaojiuguo.student.support.simple.UrlConstants;
import cn.yikaojiuguo.student.support.utils.LogUtil;
import cn.yikaojiuguo.student.support.utils.QiniuUploadUtils;
import cn.yikaojiuguo.student.support.utils.RequestUtil;
import cn.yikaojiuguo.student.support.utils.Util;
import cn.yikaojiuguo.student.support.volley.Response;
import cn.yikaojiuguo.student.ui.ask.AskDetailActivity;
import cn.yikaojiuguo.student.ui.base.BaseActivity;
import de.greenrobot.event.EventBus;

/**
 * Created by cfan_yang on 2016/1/19.
 */
public class AskChooseCourseAdapter extends SimpleBaseAdapter<Category> {

    //选中的标记位
    private int mChoose = -1;
    private List<String> mPics;
    private int mCount = 0;
    public final static int UPLOAD_WORD = 1;
    public final static int UPLOAD_PICS = 2;
    public final static int UPLOAD_VOICE = 3;
    private int mType = UPLOAD_WORD;
    private String mContent;
    private String ids = "";
    private String mAudiotime;
    private boolean mClickable = true;

    public AskChooseCourseAdapter(Context context, List<Category> list, int type, List<String>
            pics, String content, String audiotime) {
        super(context, list);
        this.mPics = pics;
        this.mType = type;
        this.mContent = content;
        this.mAudiotime = audiotime;
    }

    @Override
    public View getView(final int position, View convertView, ViewGroup parent) {
        ViewHolder holder = null;
        if (convertView == null) {
            holder = new ViewHolder();
            convertView = View.inflate(mContext, R.layout.item_choose_major, null);
            holder.tv_item = (TextView) convertView.findViewById(R.id.tv_item);
            convertView.setTag(holder);
        } else {
            holder = (ViewHolder) convertView.getTag();
        }
        holder.tv_item.setText(getItem(position).ename);
        //恢复默认样式
        convertView.setBackgroundDrawable(mContext.getResources().getDrawable(R.drawable
                .shape_item_choose_major));
        holder.tv_item.setTextColor(mContext.getResources().getColor(R.color.text_black));

        if (position == mChoose) {//如果被选中
            convertView.setBackgroundDrawable(mContext.getResources().getDrawable(R.drawable
                    .shape_item_choose_major_selected));
            holder.tv_item.setTextColor(mContext.getResources().getColor(R.color.text_white));
        }
        final Category category = getItem(position);
        if (mClickable) {
            holder.tv_item.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    mChoose = position;
                    mClickable = false;
                    notifyDataSetChanged();
                    uploadPicsOrVoice(category.id + "");
                }
            });
        } else {
            holder.tv_item.setClickable(false);
        }
        return convertView;
    }

    private void uploadPicsOrVoice(String id) {
        if (mType == UPLOAD_PICS && mPics != null) {//上传图片
            uploadPics(id);
        } else if (mType == UPLOAD_VOICE) { //上传语音
            //TODO 上传语音
            uploadVoice(id);
        } else if (mType == UPLOAD_WORD) { //只发文字
            uploadWord(id);
        }
    }

    private void uploadWord(String category) {
        ((BaseActivity) mContext).showProgressDialog("正在发送问答...");
        try {
            String requestUrl = UrlConstants.ADD_ASK + "&mid=" +
                    YiKaoApplication.getUserId() + "&content=" +
                    URLEncoder.encode(mContent, "UTF-8") +
                    "&category=" + category + "&etype=" + 1;
            RequestUtil.requestGet(requestUrl, new Response.Listener<JSONObject>() {

                @Override
                public void onResponse(JSONObject response) {
                    ((BaseActivity) mContext)
                            .dismissProgressDialog();
                    if (response != null && response.optBoolean("success")) {
                        OnAskSuccess(response);
                    }
                }
            }, null, "add ask");
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
    }

    private void uploadVoice(final String category) {
        ((BaseActivity) mContext).showProgressDialog("正在发送问答...");
        QiniuUploadUtils.uploadAskVoice((BaseActivity) mContext, new UpCompletionHandler() {
            @Override
            public void complete(String key, ResponseInfo info, JSONObject response) {
                if (info != null && info.statusCode == 200) {
                    try {
                        String picid = response.optJSONObject("data").optInt("id") + "";
                        String requestUrl = UrlConstants.ADD_ASK + "&mid=" +
                                YiKaoApplication.getUserId() + "&content=" +
                                URLEncoder.encode(mContent, "UTF-8") +
                                "&category=" + category + "&etype=" + 2 + "&audiotime="
                                + mAudiotime + "&picid=" + picid;
                        RequestUtil.requestGet(requestUrl, new Response.Listener<JSONObject>() {

                            @Override
                            public void onResponse(JSONObject response) {
                                ((BaseActivity) mContext)
                                        .dismissProgressDialog();
                                if (response != null && response.optBoolean("success")) {
                                    OnAskSuccess(response);
                                }
                            }
                        }, null, "add ask");
                    } catch (UnsupportedEncodingException e) {
                        e.printStackTrace();
                    }
                } else {
                    ((BaseActivity) mContext)
                            .dismissProgressDialog();
                    LogUtil.showInfoLog("upload error", info.error);
                }
            }
        }, null, mAudiotime);
    }

    private void uploadPics(final String category) {
        //压缩图片
        //上传图片
        new Thread() {
            @Override
            public void run() {
                //保存压缩后图片的路径
                List<String> comImgs = new ArrayList<String>();
                ((BaseActivity) mContext).runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        ((BaseActivity) mContext).showProgressDialog("正在压缩图片...");
                    }
                });

                for (String path : mPics) {
                    String outPath = YiKaoApplication.getCacheImgPath() + "/" + Util
                            .getUUID() + ".jpg";
                    comImgs.add(outPath);
                    //压缩
                    Util.compressImg(path, outPath);
                }
                ((BaseActivity) mContext).runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        ((BaseActivity) mContext).setProgressMsg("正在发送问答...");
                    }
                });
                //上传
                final List<String> picIds = new ArrayList<String>(mPics.size());
                QiniuUploadUtils.uploadAskImgs((BaseActivity) mContext, comImgs, new
                        UpCompletionHandler() {
                            @Override
                            public void complete(String key, ResponseInfo info,
                                                 JSONObject response) {
                                if (info != null && info.statusCode == 200) {
                                    //记录上传成功文件个数
                                    String id = response.optJSONObject("data").optInt("id") + "";
                                    picIds.add(id);
                                    mCount++;
                                    if (mCount == mPics.size()) {
                                        ids = ids + id;
                                        LogUtil.showInfoLog("ids", ids);
                                        try {
                                            String requestUrl = UrlConstants.ADD_ASK + "&mid=" +
                                                    YiKaoApplication.getUserId() + "&content=" +
                                                    URLEncoder.encode(mContent, "UTF-8") +
                                                    "&category=" + category + "&etype=" + 1 +
                                                    "&picid="
                                                    + ids;
                                            RequestUtil.requestGet(requestUrl, new Response
                                                    .Listener<JSONObject>() {

                                                @Override
                                                public void onResponse(JSONObject response) {
                                                    ((BaseActivity) mContext)
                                                            .dismissProgressDialog();
                                                    if (response != null && response.optBoolean
                                                            ("success")) {
                                                        OnAskSuccess(response);
                                                    }
                                                }
                                            }, null, "add ask");
                                        } catch (UnsupportedEncodingException e) {
                                            e.printStackTrace();
                                        }
                                    }
                                    ids = ids + id + ",";
                                    LogUtil.showInfoLog("response", response.toString());
                                } else {
                                    LogUtil.showInfoLog("upload error", info.error);
                                }
                            }
                        }, null);
            }
        }.start();
    }

    private void OnAskSuccess(JSONObject response) {
        LogUtil.showInfoLog("response", response
                .toString());
        Gson gson = new Gson();
        AskTeachers askTeachers = gson.fromJson
                (response.toString(), AskTeachers
                        .class);
        EventBus.getDefault().post(new
                MessageEvent("AskActivity",
                MessageEvent
                        .MessageType.FINISH));
        mContext.startActivity(AskDetailActivity
                .startAskInstance(askTeachers));
        EventBus.getDefault().post(new
                MessageEvent
                ("AskChooseSecondMajorActivity",
                        MessageEvent
                                .MessageType
                                .FINISH));
    }

    static class ViewHolder {
        TextView tv_item;
    }
}
